import { Editor, Element, Frame, useEditor } from '@craftjs/core';
import { RexProConfigProvider } from '@jeoshi-design/rex-design.other.core';
import { request } from '@umijs/max';
import { Col, Row } from 'antd';
import * as BaseComponents from './BaseComponents';
import { Container } from './components/Container';
import { SettingPanel } from './settingPanel';
import { ToolBox } from './toolBox';
import { Tools } from './tools';

type StageProps = {
  initData?: string;
};

type TemplateProps = {
  initData?: string;
  preview?: boolean;
};

const Stage: React.FC<StageProps> = ({ initData }) => {
  const { preview } = useEditor((state) => ({
    preview: !state.options.enabled,
  }));

  return (
    <RexProConfigProvider
      value={{
        apiClient: async (path, params) => {
          const res = await request('/api/mock' + path, {
            data: params,
            method: 'post',
          });

          return res.data;
        },
      }}
    >
      <Row
        style={{ height: 'calc(100vh - 64px)', border: '1px solid #d3d3d3' }}
      >
        {!preview && (
          <Col style={{ width: 200, minWidth: 200, maxWidth: 200 }}>
            <ToolBox />
          </Col>
        )}
        <Col
          flex={'1'}
          style={{ overflowX: 'auto', height: '100%', padding: '0 10px' }}
        >
          <Tools />
          <Frame data={initData}>
            {/* <Element canvas is={Container} /> */}
            <Element
              canvas
              is="div"
              style={{
                height: 'calc(100% - 52px)',
                overflow: 'auto',
              }}
            />
          </Frame>
        </Col>
        {!preview && (
          <Col
            style={{
              height: '100%',
              overflow: 'auto',
              width: 350,
              minWidth: 350,
              maxWidth: 350,
            }}
          >
            <SettingPanel />
          </Col>
        )}
      </Row>
    </RexProConfigProvider>
  );
};

const Kit: React.FC<TemplateProps> = ({ initData, preview }) => {
  const enabled = preview === undefined ? false : Boolean(Number(preview));

  return (
    <Editor resolver={{ Container, ...BaseComponents }} enabled={enabled}>
      <Stage initData={initData} />
    </Editor>
  );
};

export default Kit;
